package com.black.utils.mail;

import com.black.utils.random.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.*;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

/**
 * @author ylx
 */
@Slf4j
public class MailSender {
    protected static MailProperties mailProperties;

    public static boolean send(String subject, String msg, String to, Date sendTime) {
        try {
            if (mailProperties == null) {
                throw new RuntimeException("请先初始化邮件参数");
            }
            JavaMailSenderImpl sender = new JavaMailSenderImpl();
            sender.setHost(mailProperties.getHost());
            sender.setPort(mailProperties.getPort());
            String username = mailProperties.getUsername();
            sender.setUsername(username);
            sender.setPassword(mailProperties.getPassword());
            sender.setProtocol("smtp");
            sender.setDefaultEncoding("UTF-8");
            sender.setJavaMailProperties(mailProperties.mailProp);
            //构建邮件
            MimeMessage mimeMessage = sender.createMimeMessage();
            //不可携带附件
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, false);
            //设置邮件主题
            helper.setSubject(subject);
            //设置发件人
            helper.setFrom(username);
            //设置收件人
            helper.addTo(to);
            //设置发送日期
            helper.setSentDate(sendTime);
            //设置正文
            helper.setText(msg, true);
            log.info("发送邮件");
            sender.send(mimeMessage);
            log.info("邮件发送成功");
            return true;
        } catch (MessagingException e) {
            log.error("邮件发送失败");
        }
        return false;
    }

    public static boolean send(String subject, String msg, String to) {
        return send(subject, msg, to, new Date());
    }

    /**
     * 发送邮件
     *
     * @param subject    标题
     * @param msg        信息
     * @param to         收件人
     * @param sendTime   发送时间
     * @param singleMain 要突出的单条信息  暂不支持多条  需要手动拼
     * @return 是否发送成功
     */
    public static boolean send(String subject, String msg, String to, Date sendTime, String singleMain) {
        String str = "<html><body><h1>" + singleMain + "</h1></body></html>";
        if (msg.contains("%s")) {
            msg = String.format(msg, str);
        } else {
            msg = msg + str;
        }
        return send(subject, msg, to, sendTime);
    }

    public static boolean send(String subject, String msg, String to, String singleMain) {
        return send(subject, msg, to, new Date(), singleMain);
    }

    public static void receive_163() throws Exception {
        // 1: init 初始化
        Properties mailProp = mailProperties.getMailProp();
        mailProp.setProperty("mail.host", "pop.163.com");
        mailProp.setProperty("mail.store.protocol", "pop3");
        mailProp.setProperty("mail.user", mailProperties.getUsername());
        // 2:获取连接
        Session session = Session.getInstance(mailProp);
        session.setDebug(false);

        // 3:获取Store对象
        Store store = session.getStore();
        //POP3服务器登录认证，user我们在properties中已经指定默认
        store.connect(null, mailProperties.getPassword());

        // 4:获取收件箱内容:（电子邮件）收件箱  folder:邮件夹
        Folder folder = store.getFolder("INBOX");
        // 设置对邮件帐户的访问权限
        // Folder.READ_ONLY (只读或者1)        Folder.READ_WRITE(只写或者2)
        folder.open(Folder.READ_WRITE);

        // 5:得到邮箱帐户中的所有邮件
        Message[] messages = folder.getMessages();
        for (Message message : messages) {
            MimeMessage msg = (MimeMessage) message;
            log.info("-----------解析第" + msg.getMessageNumber() + "封邮件---------------");
            log.info("主题: " + MailParsingTool.getSubject(msg));
            log.info("发件人: " + MailParsingTool.getFrom(msg));
            log.info("收件人：" + MailParsingTool.getReceiveAddress(msg, Message.RecipientType.TO));
            log.info("发送时间：" + MailParsingTool.getSentDate(msg, null));
            log.info("是否已读：" + MailParsingTool.isSeen(msg));
            log.info("邮件优先级：" + MailParsingTool.getPriority(msg));
            log.info("是否需要回执：" + MailParsingTool.isReplySign(msg));
            log.info("邮件大小：" + msg.getSize() + "kb");
            boolean isContainerAttachment = MailParsingTool.isContainAttachment(msg);
            log.info("是否包含附件：" + isContainerAttachment);
            if (isContainerAttachment) {
                //获取文件的存储目录
                String path = MailSender.class.getClassLoader().getResource("").getPath();
                //获取文件的前缀
                String strFile = RandomUtil.generateUUID().substring(0, 8);
                MailParsingTool.saveAttachment(msg, path + strFile + "_"); //保存附件
            }
            //用来存储正文的对象
            StringBuffer content = new StringBuffer();
            //处理邮件正文
            MailParsingTool.getMailTextContent(msg, content);
            log.info("邮件正文：" + content);
            log.info("-----------第" + msg.getMessageNumber() + "封邮件解析结束------------");
        }
        // 关闭邮件夹对象
        folder.close(false);
        // 关闭连接对象
        store.close();
    }

    public static void init(MailProperties mailProperties) {
        MailSender.mailProperties = mailProperties;
    }

    public static void init(String resource) {
        MailSender.mailProperties = new MailProperties(resource);
    }
}
